using Microsoft.EntityFrameworkCore;
using MyHomeworkWebAPi.Models.DTOs;
using MyHomeworkWebAPi.Models.ef;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace MyHomeworkWebAPi.Services
{
    public class LogService
    {
        private readonly SecondHandTradingPlatformContext _context;

        public LogService(SecondHandTradingPlatformContext context)
        {
            _context = context;
        }

        public async Task<List<LogDTO>> GetAllAsync()
        {
            var logs = await _context.Logs.ToListAsync();
            return logs.Select(l => new LogDTO
            {
                Id = l.Id,
                UserId = l.UserId,
                Detail = l.Detail,
                CreateTime = l.CreateTime
            }).ToList();
        }

        public async Task<LogDTO> GetByIdAsync(Guid id)
        {
            var log = await _context.Logs.FindAsync(id);
            if (log == null)
            {
                return null;
            }
            return new LogDTO
            {
                Id = log.Id,
                UserId = log.UserId,
                Detail = log.Detail,
                CreateTime = log.CreateTime
            };
        }

        public async Task<LogDTO> CreateAsync(LogDTO logDTO)
        {
            var log = new Log
            {
                Id = Guid.NewGuid(),
                UserId = logDTO.UserId,
                Detail = logDTO.Detail,
                CreateTime = DateTime.Now
            };
            _context.Logs.Add(log);
            await _context.SaveChangesAsync();
            return new LogDTO
            {
                Id = log.Id,
                UserId = log.UserId,
                Detail = log.Detail,
                CreateTime = log.CreateTime
            };
        }

        public async Task<LogDTO> UpdateAsync(Guid id, LogDTO logDTO)
        {
            var log = await _context.Logs.FindAsync(id);
            if (log == null)
            {
                return null;
            }
            log.UserId = logDTO.UserId;
            log.Detail = logDTO.Detail;
            await _context.SaveChangesAsync();
            return new LogDTO
            {
                Id = log.Id,
                UserId = log.UserId,
                Detail = log.Detail,
                CreateTime = log.CreateTime
            };
        }

        public async Task<bool> DeleteAsync(Guid id)
        {
            var log = await _context.Logs.FindAsync(id);
            if (log == null)
            {
                return false;
            }
            _context.Logs.Remove(log);
            await _context.SaveChangesAsync();
            return true;
        }
    }
} 